from launch import LaunchDescription
from launch_ros.actions import Node
from launch.actions import DeclareLaunchArgument
from launch.substitutions import LaunchConfiguration

def generate_launch_description():
    # Launch arguments 
    port_name_arg=DeclareLaunchArgument("port_name", default_value="ttyS1", description="Serial port name")
    baudrate_arg=DeclareLaunchArgument("baudrate", default_value="115200", description="Serial port baudrate")
    correct_factor_vx_arg=DeclareLaunchArgument("correct_factor_vx", default_value="1.0", description="Velocity correction factor")
    correct_factor_wz_arg=DeclareLaunchArgument("correct_factor_wz", default_value="1.0", description="Angular velocity correction factor")
    pub_odom_tf_arg=DeclareLaunchArgument("pub_odom_tf", default_value="true", description="Publish odometry transform")
    use_imu_arg=DeclareLaunchArgument("use_imu",default_value="false",description="Use IMU data")
    auto_stop_on_arg=DeclareLaunchArgument("auto_stop_on",default_value="true",description="Auto stop on signal")

    # Nodes
    robot_base_node=Node(
        package="robot_base",
        executable="robot_base_exec",
        parameters=[
            {"port_name": LaunchConfiguration("port_name")},
            {"baudrate": LaunchConfiguration("baudrate")},
            {"correct_factor_vx": LaunchConfiguration("correct_factor_vx")},
            {"correct_factor_wz": LaunchConfiguration("correct_factor_wz")},
            {"pub_odom_tf": LaunchConfiguration("pub_odom_tf")},
            {"use_imu": LaunchConfiguration("use_imu")},
            {"auto_stop_on": LaunchConfiguration("auto_stop_on")}
        ],
        output="screen"
    )
    
    # 发布机器人本体坐标系(base_link)到机器人本体在地面的投影点(base_footprint)之间的tf变换
    base_footprint_tf = Node(
        package='tf2_ros',
        executable='static_transform_publisher',
        arguments=["--x", "0.0", "--y", "0.0", "--z", "0.05325", "--roll", "0.0", "--pitch", "0.0", "--yaw", "0.0", "--frame-id", "base_footprint", "--child-frame-id", "base_link"]
    )

    imu_tf = Node(
        package='tf2_ros',
        executable='static_transform_publisher',
        arguments=["--x", "0.0", "--y", "0.0", "--z", "0.0", "--roll", "0.0", "--pitch", "0.0", "--yaw", "0.0", "--frame-id", "base_link", "--child-frame-id", "imu_link"]
    )


    ld=LaunchDescription()
    ld.add_action(port_name_arg)
    ld.add_action(baudrate_arg)
    ld.add_action(correct_factor_vx_arg)
    ld.add_action(correct_factor_wz_arg)
    ld.add_action(pub_odom_tf_arg)
    ld.add_action(use_imu_arg)
    ld.add_action(auto_stop_on_arg)
    ld.add_action(robot_base_node)
    ld.add_action(base_footprint_tf)
    ld.add_action(imu_tf)

    return ld